package service;

import dao.RatingDAO;
import dao.UserDAO;
import dao.MovieDAO;
import domain.Movie;
import domain.User;
import ex.DatabaseException;
import ex.RegistrationFailedException;

public class RatingService {

	UserDAO userDao=new UserDAO();
	MovieDAO movieDao = new MovieDAO();
	RatingDAO rDao=new RatingDAO();
	public void rateUser(User from, User to, int rate) throws DatabaseException{
		long rateCount=to.getPopularity();
		double newRate=2;
		if(to.getPopularity()==0){
			newRate=rate;
			rateCount++;
		}
		else{
			double oldRate=to.getRating();
			double totalRate=oldRate*(double)rateCount;
			
			totalRate+=rate;
			rateCount++;
			
			newRate=totalRate/(double)rateCount;			
		}
		//rateCount++;
		
		to.setRating(newRate);
		to.setPopularity(rateCount);
		
		userDao.editUser(to);
		rDao.insertUserRating(from.getUid(), to.getUid(), rate);
	}
	
	public void rateMovie(User from, Movie to, int rate) throws DatabaseException{
		int rateCount=to.getPopularity();
		double newRate=2;
		if(to.getPopularity()==0){
			newRate=rate;
			rateCount++;
		}
		else{
			double oldRate=to.getRating();
			double totalRate=oldRate*(double)rateCount;
			
			totalRate+=rate;
			rateCount++;
			
			newRate=totalRate/(double)rateCount;			
		}
		//rateCount++;
		
		to.setRating(newRate);
		to.setPopularity(rateCount);
		
		movieDao.updateMovie(to);
		rDao.insertMovieRating(from.getUid(), to.getMid(), rate);
	}
	
	public boolean hasRatedBefore(User u1, User u2) throws DatabaseException{
		RatingDAO rDao = new RatingDAO();
		
		return rDao.selectRatingByUid1Uid2(u1.getUid(), u2.getUid()) != 0; 
		
	}
	
	public boolean hasRatedBefore(User u1, Movie m) throws DatabaseException{
		RatingDAO rDao = new RatingDAO();
		
		return rDao.selectRatingByUid1Mid2(u1.getUid(), m.getMid()) != 0; 
		
	}
	
}
